// 获取栏目名称列表
var getMenuStore = Ext.create('Ext.data.Store', {
     model: 'app.model.MenuModel',
     proxy: {
         type: 'ajax',
         url: 'getAllMenuListStore',
         reader: {
             type: 'json',
             root: 'data'
         }
     },
     autoLoad: true
 });

// 根据站点名称
var getSiteStore = Ext.create('Ext.data.Store', {
    model: 'app.model.SiteModel',
    proxy: {
        type: 'ajax',
        url: 'getAllSiteListStore',
        reader: {
            type: 'json',
            root: 'data'
        }
    },
    autoLoad: false
});

// 根据站点名称获取分类名称
var getSiteCategoryStore = Ext.create('Ext.data.Store', {
    model: 'app.model.SiteCategoryModel',
    proxy: {
        type: 'ajax',
        url: "getCategoryNameBySiteIdStore?siteId=-1",
        reader: {
            type: 'json',
            root: 'data'
        }
    },
    autoLoad: false
});



var tbar = Ext.create('Ext.toolbar.Toolbar', {
	dock : 'top',
	layout: {  
        overflowHandler: 'Menu'  
    },  
	items : [{
		id:'menuId',
		xtype : 'combo',
		fieldLabel : '栏目名称',
		labelWidth : 60,
		store : getMenuStore,
		displayField : 'menuName',
		valueField : 'id',
		name : 'menuId',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 190
	},{
		id:'siteId',
		xtype : 'combo',
		fieldLabel : '站点名称',
		labelWidth : 60,
		store : getSiteStore,
		displayField : 'siteName',
		valueField : 'id',
		name : '',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 190,
		listeners:{
	        'change': function(val){
    			// 根据站点id获取分类信息
	        	var siteId = val.value;
	        	
				getSiteCategoryStore.proxy.url = 'getCategoryNameBySiteIdStore?siteId='+siteId,
				getSiteCategoryStore.load({
				    scope: this,
				    callback: function(records, operation, success) {
				    	if(records[0] != null){
				    		Ext.getCmp("siteCategoryId").select(records[0].raw.id);
				    		return;
				    	}
				    }
				});
				//search();
		  }
	    }
	},{
		id:'siteCategoryId',
		xtype : 'combo',
		fieldLabel : '分类名称',
		labelWidth : 60,
		store : getSiteCategoryStore,
		displayField : 'categoryName',
		valueField : 'id',
		name : 'categoryId',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 190,
		listeners:{
	        'change': function(val){
    			//search();
    		  }
	    }
	},{
		text : '查询',
		handler : function() {
			search();
		}
	},{
		text : '重置',
		handler : function() {
			Ext.getCmp("menuId").select("");
			Ext.getCmp("siteId").select("");
			Ext.getCmp("siteCategoryId").select("");
			search();
		}
	},{
		xtype : 'button',
		text : '绑定关系',
		handler : function() {
			addBindRelation();
		}
	}]

});

// 查询  抽象出来  统一调用
function search(){
	var menuId = Ext.getCmp("menuId").getValue()==-1?'':Ext.getCmp("menuId").getValue();
	var siteId = Ext.getCmp("siteId").getValue()==-1?'':Ext.getCmp("siteId").getValue();
	var siteCategoryId = Ext.getCmp("siteCategoryId").getValue()==-1?'':Ext.getCmp("siteCategoryId").getValue();
	
	var bindRelationStore = Ext.getCmp("bindRelationGrid").getStore();
	bindRelationStore.load({
		params : {
			menuId:menuId,
			siteId: siteId,
			siteCategoryId:siteCategoryId,
			page : 1,
			start : 0,
			limit : 20
        }
	});
	bindRelationGrid.currentPage=1
}


Ext.define("app.view.BindRelationGrid", {
			extend : "Ext.grid.Panel",
			xtype: 'cell-editing',
			alias : "widget.bindRelationGrid",
			id : "bindRelationGrid",
			width:700,
			height:350,
			viewConfig:{
		         loadMask:false  // grid去掉加载中的提示
		    },
			selModel : {
				//selType : "checkboxmodel"
			},
			border : 0,
			multiSelect : true,
			frame : false, // 不要边框
			tbar : tbar,
			bbar : {
				xtype : 'pagingtoolbar',
				store : 'BindRelationStore',
				dock : 'bottom',
				displayInfo : true
			},
			viewConfig:{  
		        enableTextSelection:true  // 文本可选择
		    },
			enableKeyNav : true,
			columnLines : true,
			forceFit :true, // 宽度自适配
			columns : [{
						text:"序号",
						dataIndex:"id",
						width:20
					},{
						text : "栏目名称",
						dataIndex : "menuName",
						width : 120,
		                editor: {
		                	xtype : "textfield",
		                    allowBlank: false
		                }
					},{
						text : "站点名称",
						dataIndex : "siteName",
						width : 120,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
						text : "分类名称",
						dataIndex : "categoryName",
						width : 120,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
		                xtype: 'actioncolumn',
		                width: 20,
		                tdCls: 'action',  
		                text: '操作',  
		                sortable: false,
		                menuDisabled: true,
		                items: [{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/close.png',
		                    tooltip: '解除绑定',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                    	var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        this.unbindRealtionById(grid,id);
		                    },
		                    getClass: function(v, meta, record) {
		                    	return '';
		                    }
		                }
		                ]
		            }],
			listeners: { 
			},					
			initComponent : function() {
				// 可编辑插件
				this.callParent(arguments);
			},
			store : "BindRelationStore"
});


//根据id解除绑定
function unbindRealtionById(grid,id){
	var store = grid.getStore();
	Ext.Ajax.request({
		url : "unbindRealtionById",
		params : {
			id : id
		},
		method : "POST",
		timeout : 4000,
		success : function(response, opts) {
			var result = eval('('+response.responseText+')');
			if(result.resultCode == 'success'){
				// 刷新grid
				store.load();
				Ext.example.msg('', '解除绑定成功', '');
			}else{
				Ext.example.msg('', '解除绑定失败', '');
			}
		}
	});
}

//绑定关系
function addBindRelation(){
	var store = Ext.getCmp("bindRelationGrid").getStore();
    var win = Ext.create('Ext.window.Window', {
    	autoShow: false,
        title: '绑定关系',
        width: 400,
        height: 320,
        minWidth: 300,
        minHeight: 200,
        layout: 'fit',
        plain:true,
        modal: false,  // 模态
        collapsible: true, //允许缩放条  
        closeAction: 'destroy', 
        autoScroll: true,
        maximizable :true,
        loader: {
            url:'loadBindRelationInfo',
            scripts: true,
            autoLoad: true
        },
        listeners:{
        },
        buttonAlign: "center",  
        buttons: [{
            text: '保存',
            handler: function() {
            	// 校验
            	if(validateSave()){
                	var dataParm = decodeURIComponent($("#add_bind_relation_form").serialize(),true);
                	dataParm = encodeURI(encodeURI(dataParm));
                	$.ajax({
            			url : './saveBindRelation?data='+Math.random(),
            			data: dataParm,
            			type : "post",
            			dataType : "json",
            			async: true,
            			success : function(data) {
            				if (data.resultCode == 'error') {
            					Ext.example.msg('','绑定关系失败!', '');
            					return;
            				} else if (data.resultCode == 'fail') {
            					Ext.example.msg('','不可重复绑定栏目分类关系', '');
            					return;
            				} else if (data.resultCode == 'success') {
            					// 弹出新增成功消息框 
            					Ext.example.msg('', '绑定关系成功', '');
            					store.load();
            					// 关闭窗口
            					win.close();
            				}
            			}
            		});
            	}
            }
        },{
            text: '取消',
            handler: function() {
            	// 关闭窗口
            	win.close();
            }
        }]
    });
    win.show();
}
